package m.jclecai.com.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import butterknife.Unbinder;
import m.jclecai.com.R;
import m.jclecai.com.activity.AppointmentOrderActivity;
import m.jclecai.com.activity.follow.FollowListActivity;
import m.jclecai.com.activity.follow.HitListActivity;
import m.jclecai.com.activity.follow.HotOrderDetailActivity;
import m.jclecai.com.activity.follow.HotPeopleInfoActivity;
import m.jclecai.com.activity.follow.HotPeopleListActivity;
import m.jclecai.com.activity.follow.MineConcernActivity;
import m.jclecai.com.adapter.base.ViewHolerAdapter;
import m.jclecai.com.adapter.holder.ViewHolder;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.Response.ResHotOrderList;
import m.jclecai.com.bean.Response.ResHotPeople;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.rounded.RoundedImageView;

/**
 * Created by Dinosa on 2017/11/10.
 */

public class FollowFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2 {


    @Nullable
    @BindViews({R.id.iv_hot_person1
            , R.id.iv_hot_person2
            , R.id.iv_hot_person3
            , R.id.iv_hot_person4
            , R.id.iv_hot_person5
    })
    public List<RoundedImageView> mIvPersons;

    @Nullable
    @BindViews({R.id.rl_recomment_one
            , R.id.rl_recomment_two
            , R.id.rl_recomment_three
            , R.id.rl_recomment_four
            , R.id.rl_recomment_five
    })
    public List<View> mRlRecomment;

    @Nullable
    @BindViews({R.id.iv_user_rank1
            , R.id.iv_user_rank2
            , R.id.iv_user_rank3
            , R.id.iv_user_rank4
            , R.id.iv_user_rank5
    })
    public List<ImageView> mIvUserRanks;

    @Nullable
    @BindViews({R.id.tv_hot_person1
            , R.id.tv_hot_person2
            , R.id.tv_hot_person3
            , R.id.tv_hot_person4
            , R.id.tv_hot_person5
    })
    public List<TextView> mTvPersons;

    PullToRefreshListView mPrlListView;
    @BindView(R.id.ll_hit)
    LinearLayout mLlHit;

    @BindView(R.id.ll_profit)
    LinearLayout mLlProfit;

    @BindView(R.id.ll_my_concern)
    LinearLayout mLlMyConcern;

    @BindView(R.id.ll_my_reservation)
    LinearLayout mLlMyReservation;

    @BindView(R.id.tv_more_hot_people)
    TextView mTvMoreHotPeople;

    int mPage = 1;
    @BindView(R.id.rg_follow_order_option)
    RadioGroup mRgFollowOrderOption;
    Unbinder unbinder;
    private HotOrderAdapter mHotOrderAdapter;
    private String mCurHotOrderSort;

    @BindView(R.id.rb_plan_money)
    RadioButton mRbPlanMoney;

    @BindView(R.id.rb_follow_order_hot)
    RadioButton mRbFollowOrderHot;

    @BindView(R.id.rb_order_time)
    RadioButton mRbOrderTime;

    @BindView(R.id.rg_follow_option)
    RadioGroup mViewTitle;


    @BindView(R.id.rb_plan_money2)
    RadioButton mRbPlanMoney2;

    @BindView(R.id.rb_follow_order_hot2)
    RadioButton mRbFollowOrderHot2;

    @BindView(R.id.rb_order_time2)
    RadioButton mRbOrderTime2;

    private ListView mListView;

    @Override
    public int getLayoutId() {
        return R.layout.activity_follow;
    }

    @Override
    public void initView() {
        setTitle("复制跟单");
    }

    public void initLoadingView(View vBody) {
        mPrlListView = (PullToRefreshListView) vBody.findViewById(R.id.prl_list_view);
        mListView = mPrlListView.getRefreshableView();

        final View header = View.inflate(getActivity(), R.layout.item_follow_header, null);
        mListView.addHeaderView(header);

        //view.addFooterView(View.inflate(getActivJczity(), R.layout.item_follow_footer, null));
    }


    @Override
    public void initData() {

        mCurHotOrderSort = "money";


        mHotOrderAdapter = new HotOrderAdapter(null);
        mPrlListView.setAdapter(mHotOrderAdapter);
        mPrlListView.setOnRefreshListener(this);
        mPrlListView.setMode(PullToRefreshBase.Mode.BOTH);
        showDialog();
        requestData();
        initRadioButtonDrawable();

        for (int i = 0; i < mViewTitle.getChildCount(); i++) {
            RadioButton childAt = (RadioButton) mViewTitle.getChildAt(i);
            alterBound(childAt);
        }

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                boolean isShow = false;
                View headerView = mListView.getChildAt(firstVisibleItem);
                if (headerView != null && mViewTitle != null && firstVisibleItem == 1) {
                    isShow = (headerView.getTop() - getViewTitleHeight()) < 0;
                }
                if (firstVisibleItem > 1 || isShow) {
                    mViewTitle.setVisibility(View.VISIBLE);
                } else {
                    mViewTitle.setVisibility(View.GONE);
                }
            }
        });
    }

    public int getViewTitleHeight() {
        if (mViewTitle.getHeight() != 0) {
            return mViewTitle.getHeight();
        } else {
            int measureSpec = View.MeasureSpec.makeMeasureSpec(1 << 20 - 2, View.MeasureSpec.AT_MOST);
            mViewTitle.measure(measureSpec, measureSpec);
            return mViewTitle.getMeasuredHeight();
        }
    }

    private void initRadioButtonDrawable() {

        alterBound(mRbFollowOrderHot);
        alterBound(mRbOrderTime);
        alterBound(mRbPlanMoney);

    }

    public void alterBound(RadioButton button) {
        //挨着给每个RadioButton加入drawable限制边距以控制显示大小
        Drawable[] drawables = button.getCompoundDrawables();
        //获取drawables，2/5表示图片要缩小的比例
        Rect r = new Rect(0, 0, drawables[2].getMinimumWidth() * 2 / 4, drawables[2].getMinimumHeight() * 2 / 4);
        //定义一个Rect边界
        drawables[2].setBounds(r);
        //给每一个RadioButton设置图片大小
        button.setCompoundDrawables(null, null, drawables[2], null);
    }


    private void requestData() {
        reqeustHotUser();
        requestHotOrder(mCurHotOrderSort);
    }

    private void requestHotOrder(String type) {
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("order", type);
        paramsMap.put("page", mPage + "");
        //这里我们请求热门跟单;
        HttpManager.postAsyn(Constant_Url.FOLLOW_HOT_ORDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络加载异常!!!");
                mPrlListView.onRefreshComplete();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                mPrlListView.onRefreshComplete();
                if (!TextUtils.isEmpty(response)) {
                    if (mPrlListView != null) {
                        mPrlListView.onRefreshComplete();
                    }
                    ResHotOrderList resHotPeople = FastOk.get(response, ResHotOrderList.class);
                    if (resHotPeople != null && "0".equals(resHotPeople.getStatus())) {

                        if (mPage > resHotPeople.getPages()) {
                            DisPlay("没有更多数据！！！");
                        } else {
                            if (mPage == 1) {
                                //updateHotOrder(resHotPeople.getRecords());
                                mHotOrderAdapter.refersh(resHotPeople.getRecords());
                            } else {
                                mHotOrderAdapter.addAll(resHotPeople.getRecords());
                            }
                            mPage++;
                        }

                    } else {
                        if (resHotPeople != null) {

                            DisPlay(resHotPeople.getMessage());
                        } else {
                            DisPlay("网络异常!!!");
                        }
                    }
                } else {
                    DisPlay("网络异常!!");
                }
            }
        }, paramsMap);
    }

    @OnClick(R.id.tv_more_hot_people)
    public void onClickMoreHotPeople(View view) {
        Intent intent = new Intent(getActivity(), HotPeopleListActivity.class);
        startActivity(intent);
    }


    /**
     * 更新热门
     */
    private void updateHotOrder(List<ResHotOrderList.HotOrderBean> hotOrderBeen) {

        mHotOrderAdapter.addAll(hotOrderBeen);

    }


    private void reqeustHotUser() {


        HttpManager.getAsyn(Constant_Url.HOT_PEOPLE_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常!!!");
            }

            @Override
            public void onResponse(String response) {
                if (!TextUtils.isEmpty(response)) {

                    ResHotPeople resHotPeople = FastOk.get(response, ResHotPeople.class);
                    if (resHotPeople != null && "0".equals(resHotPeople.getStatus())) {

                        updateHotPeople(resHotPeople.getRecords());

                    } else {
                        if (resHotPeople != null) {
                            DisPlay(resHotPeople.getMessage());
                        } else {
                            DisPlay("网络异常");
                        }
                    }
                } else {
                    DisPlay("网络异常!!");
                }
            }
        });
    }

    /**
     * 更新名人
     *
     * @param hotPerson
     */
    private void updateHotPeople(final List<ResHotPeople.HotPeopleBean> hotPerson) {

        for (int i = 0; i < mIvPersons.size(); i++) {
            ResHotPeople.HotPeopleBean hotPersonBean = null;
            try {
                hotPersonBean = hotPerson.get(i);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (hotPersonBean == null) {
                //这里将对应的布局进行一个隐藏；
                mRlRecomment.get(i).setVisibility(View.INVISIBLE);
                continue;
            } else {
                mRlRecomment.get(i).setVisibility(View.VISIBLE);
            }

            if (i > mIvPersons.size() - 1) {
                break;
            }
            //Glide.with(this).load(hotPersonBean.getUser_face()).placeholder(R.drawable.user_pic).into(mIvPersons.get(i));
            Glide.with(this).load(hotPersonBean.getUser_face()).into(mIvPersons.get(i));
            mTvPersons.get(i).setText(hotPersonBean.getUsername());
            if (hotPersonBean.getUser_rank() > 0) {

                mIvUserRanks.get(i).setVisibility(View.VISIBLE);

            } else {
                mIvUserRanks.get(i).setVisibility(View.INVISIBLE);
            }
            //设置变量
            final int finalI = i;
            mIvPersons.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里我们要进行一个跳转；
                    startActivity(HotPeopleInfoActivity.getIntent(getActivity(), hotPerson.get(finalI).getUser_id()));
                }
            });
        }
    }

    @Override
    public void initListener() {
        RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                //这里我们做相应的逻辑
                switch (checkedId) {
                    case R.id.rb_plan_money:
                    case R.id.rb_plan_money2:
                        showDialog();
                        mPage = 1;
                        mHotOrderAdapter.clear();
                        mCurHotOrderSort = "money";
                        requestHotOrder("money");

                        mRbPlanMoney.setChecked(true);
                        mRbPlanMoney2.setChecked(true);
                        break;
                    case R.id.rb_follow_order_hot:
                    case R.id.rb_follow_order_hot2:
                        showDialog();
                        mPage = 1;
                        mHotOrderAdapter.clear();
                        mCurHotOrderSort = "hot";
                        requestHotOrder("hot");

                        mRbFollowOrderHot.setChecked(true);
                        mRbFollowOrderHot2.setChecked(true);
                        break;
                    case R.id.rb_order_time:
                    case R.id.rb_order_time2:
                        showDialog();
                        mPage = 1;
                        mHotOrderAdapter.clear();
                        mCurHotOrderSort = "time";
                        requestHotOrder("time");

                        mRbOrderTime.setChecked(true);
                        mRbOrderTime2.setChecked(true);
                        break;
                }
            }
        };

        mRgFollowOrderOption.setOnCheckedChangeListener(onCheckedChangeListener);
        mViewTitle.setOnCheckedChangeListener(onCheckedChangeListener);
    }

    @OnClick({R.id.ll_hit, R.id.ll_profit, R.id.ll_my_concern, R.id.ll_my_reservation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_hit:
                //命中榜
                startActivity(HitListActivity.getIntent(getActivity(), "命中榜", "nums"));
                break;
            case R.id.ll_profit:
                //盈利榜
                startActivity(HitListActivity.getIntent(getActivity(), "盈利榜", "money"));
                break;
            case R.id.ll_my_concern:
                //我的关注
                startActivity(new Intent(getActivity(), MineConcernActivity.class));
                break;
            case R.id.ll_my_reservation:
                //我的发单；这里弄成一个网页；
                //Intent intent = WebHelperActivity.getInstance(getActivity(), "http://m.cai310.net/gd/billingf.html", false, "预约发单");
                //startActivity(intent);
                //startActivity(NewWebViewHelperActivity.getIntent(getActivity(), "http://m.cai310.net/gd/billingf.html","预约发单"));
                startActivity(new Intent(getActivity(), AppointmentOrderActivity.class));
                break;
        }
    }

    /**
     * 20180305需求跳转跟单搜索
     */
    @OnClick(R.id.llSearch)
    void toFollowSearch() {
        startActivity(new Intent(getActivity(), FollowListActivity.class));
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        mHotOrderAdapter.clear();
        mPage = 1;
        requestHotOrder(mCurHotOrderSort);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        requestData();
    }

    public void getView(int startPosition) {

        mHotOrderAdapter.getView(startPosition, null, mListView);

    }


    public class HotOrderAdapter extends ViewHolerAdapter<FollowViewHolder> {

        public List<ResHotOrderList.HotOrderBean> mOrderBeanList;


        public HotOrderAdapter(List<ResHotOrderList.HotOrderBean> orderBeanList) {
            mOrderBeanList = orderBeanList == null ? new ArrayList<ResHotOrderList.HotOrderBean>() : orderBeanList;
        }

        @Override
        public FollowViewHolder onCreateViewHolder(int position, ViewGroup parent) {
            return new FollowViewHolder(getActivity(), R.layout.item_follow_order);
        }

        @Override
        public void onBindViewHolder(int position, FollowViewHolder followViewHolder) {
            followViewHolder.init(mOrderBeanList.get(position));
        }

        public void refersh(List<ResHotOrderList.HotOrderBean> datas) {
            mOrderBeanList.clear();
            mOrderBeanList.addAll(datas);
            notifyDataSetChanged();
        }

        public void addAll(List<ResHotOrderList.HotOrderBean> datas) {
            mOrderBeanList.addAll(datas);
            notifyDataSetChanged();
        }

        public void clear() {
            mOrderBeanList.clear();
            notifyDataSetChanged();
        }

        public void setData(List<ResHotOrderList.HotOrderBean> data) {
            mOrderBeanList = data;
        }

        public List<ResHotOrderList.HotOrderBean> getData() {
            return mOrderBeanList;
        }

        @Override
        public int getCount() {
            return mOrderBeanList.size();
        }
    }

    public class FollowViewHolder extends ViewHolder {

        @BindView(R.id.iv_user_icon)
        RoundedImageView mIvUserIcon;

        @BindView(R.id.tv_username)
        TextView mTvUsername;

        @BindView(R.id.tv_history_win)
        TextView mTvHistoryWin;

        @BindView(R.id.tv_win_total_money)
        TextView mTvWinTotalMoney;

        @BindView(R.id.tv_group_buy_title)
        TextView mTvGroupBuyTitle;

        @BindView(R.id.tv_group_buy_time)
        TextView mTvGroupBuyTime;

        @BindView(R.id.tv_least)
        TextView mTvLeast;

        @BindView(R.id.tv_group_buy_des)
        TextView mTvGroupBuyDes;

        @BindView(R.id.tv_group_buy_money)
        TextView mTvGroupBuyMoney;

        @BindView(R.id.tv_follow_number)
        TextView mTvFollowNumber;

        @BindView(R.id.tv_follow)
        TextView mTvFollow;

        @BindView(R.id.rl_award_number)
        TextView mRlAwardNumber;

        @BindView(R.id.tv_unit_award)
        TextView mTvUnitAward;

        @BindView(R.id.rl_award_bg)
        RelativeLayout mRlAwardBg;

        @BindView(R.id.iv_user_rank)
        ImageView mIvUserRank;

        @BindView(R.id.ll_user)
        View mLluser;

        @BindView(R.id.ll_item_order)
        View mLlItemorder;


        public FollowViewHolder(Context context, @LayoutRes int resource) {
            super(context, resource);
        }

        public void init(final ResHotOrderList.HotOrderBean hotOrderBean) {

            mTvUnitAward.setText(hotOrderBean.getReturnrate() + "倍");

            //上半部分的逻辑
            Glide.with(FollowFragment.this).load(hotOrderBean.getUser_face()).into(mIvUserIcon);
            mTvUsername.setText(hotOrderBean.getUsername());
            mTvWinTotalMoney.setText(Html.fromHtml("<html><body>创造价值:<font color='red'>" + hotOrderBean.getWinmoneys_total() + "</font></body></html>"));


            if (hotOrderBean.getUser_rank() > 0) {
                mIvUserRank.setVisibility(View.VISIBLE);
            } else {
                mIvUserRank.setVisibility(View.INVISIBLE);
            }

            StringBuffer hw = new StringBuffer("0 中 0");
            if (hotOrderBean != null && !TextUtils.isEmpty(hotOrderBean.getMilitary_total())) {
                hw.delete(0, hw.length());
                hw.append(" " + hotOrderBean.getMilitary_total() + " ");
            }
            if (hotOrderBean.getMilitary_title().equals("")) {
                mTvHistoryWin.setVisibility(View.GONE);
            } else {
                mTvHistoryWin.setVisibility(View.VISIBLE);
                mTvHistoryWin.setText(Html.fromHtml(hotOrderBean.getMilitary_title()));
            }
//            mTvHistoryWin.setText(Html.fromHtml(hw.toString().split("/")[1] + "连中"));
            mTvHistoryWin.setTextSize(15);
//            mTvHistoryWin.setText(hotOrderBean.getUsertitle());

            //下半部分的逻辑
            mTvGroupBuyTitle.setText(hotOrderBean.getLotteryname());
            mTvGroupBuyTime.setText(hotOrderBean.getEndtime());
            mTvLeast.setText(hotOrderBean.getFollow_minmoney() + "元起投");
            mTvGroupBuyDes.setText(hotOrderBean.getTitle());

            mTvGroupBuyMoney.setText("自购：" + hotOrderBean.getOne_money() + "元");
            mTvFollowNumber.setText("跟单:" + hotOrderBean.getFollow_count() + "人");

            if ("1".equals(hotOrderBean.getState())) {
                mRlAwardBg.setVisibility(View.VISIBLE);
                //已撤单
                mTvFollow.setVisibility(View.INVISIBLE);
                mRlAwardBg.setBackgroundResource(R.drawable.follow_no_win_img);
                mTvFollow.setOnClickListener(null);
                mRlAwardNumber.setVisibility(View.INVISIBLE);
            } else if ("2".equals(hotOrderBean.getState())) {
                //未中奖
                mRlAwardBg.setVisibility(View.VISIBLE);
                mRlAwardBg.setBackgroundResource(R.drawable.follow_no_win_img);
                mTvFollow.setVisibility(View.INVISIBLE);
                mRlAwardNumber.setVisibility(View.INVISIBLE);
                mTvFollow.setOnClickListener(null);
            } else if ("3".equals(hotOrderBean.getState())) {
                //已经中奖
                mRlAwardBg.setVisibility(View.VISIBLE);
                mRlAwardBg.setBackgroundResource(R.drawable.follow_win);
                mRlAwardNumber.setVisibility(View.VISIBLE);
                mRlAwardNumber.setText("￥" + hotOrderBean.getWin_money());
                mTvFollow.setVisibility(View.INVISIBLE);
                mTvFollow.setOnClickListener(null);

//                mTvFollow.setOnClickListener(new OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        //这里要执行的逻辑就是立即跟单
//                        startActivity(HotOrderDetailActivity.getIntent(getActivity(), hotOrderBean.getId()));
//                    }
//                });
            } else {
                //这里表示是可跟单；
                mRlAwardBg.setVisibility(View.INVISIBLE);
                mTvFollow.setOnClickListener(null);
                mRlAwardNumber.setVisibility(View.INVISIBLE);

                if (hotOrderBean.getCan_follow() > 0) {
                    mTvFollow.setVisibility(View.VISIBLE);
                    mTvFollow.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //这里要执行的逻辑就是立即跟单
                            startActivity(HotOrderDetailActivity.getIntent(getActivity(), hotOrderBean.getId()));
                        }
                    });
                } else {
                    mTvFollow.setVisibility(View.INVISIBLE);
                }
            }

            mLlItemorder.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //点击条目进入订单详情页面；
                    startActivity(HotOrderDetailActivity.getIntent(getActivity(), hotOrderBean.getId()));
                }
            });
            mLluser.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //点击头像，进入个人详情的页面
                    startActivity(HotPeopleInfoActivity.getIntent(getActivity(), hotOrderBean.getUser_id()));
                }
            });
        }
    }
}
